const initialState = {
  articleList: {} as { [key: number]: { results: ArticleType[]; pre_timestamp: number } },
  // 1. 设置state和初始值，并且设置初始值类型
  detail: {} as ArticleDetail,
};
export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    // 2 。复制时后台没有返回该字段，手动加上
    images: string[];
  };
};
export type ArticleDetail = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};
// 定义actionType类型
type ActionType =
  | {
      type: 'article/saveList';
      payload: { channel_id: number; pre_timestamp: number; results: ArticleType[] };
    }
  | {
      type: 'article/updateListById';
      payload: { channel_id: number; pre_timestamp: number; results: ArticleType[] };
    }
  // 2. 扩展actionType的类型
  | { type: 'article/saveDetail'; payload: ArticleDetail };
export default function articleReducer(state = initialState, actions: ActionType) {
  switch (actions.type) {
    case 'article/saveList':
      return {
        ...state,
        articleList: {
          // 💥 解构赋值旧的数据
          ...state.articleList,
          [actions.payload.channel_id]: {
            pre_timestamp: actions.payload.pre_timestamp,
            results: actions.payload.results,
          },
        },
      };
    case 'article/updateListById': // {id:1 result, timetaamp}
      const oldData = state.articleList[actions.payload.channel_id];
      let newList = [...oldData.results, ...actions.payload.results];
      console.log(oldData);
      return {
        ...state,
        articleList: {
          ...state.articleList,
          [actions.payload.channel_id]: {
            pre_timestamp: actions.payload.pre_timestamp,
            results: newList,
          },
        },
      };
    case 'article/saveDetail':
      return {
        ...state,
        detail: { ...actions.payload },
      };
    default:
      return state;
  }
}
